package com.tiance.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.tiance.enums.ErrorCodeEnum;
import com.tiance.enums.OperateTypeEnum;
import com.tiance.exception.BusinessException;
import com.tiance.integration.config.CommonProperties;
import com.tiance.integration.wechat.JsWechatConfig;
import com.tiance.integration.wechat.JsapiTicket;
import com.tiance.integration.wechat.WechatClient;
import com.tiance.integration.wechat.WechatPayUtil;
import com.tiance.utils.SHA1Util;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：会员管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/front")
public class WechatController extends FrontController {
    private static String LOG_PREFIX ="MemberController| 微信控制器===>";


    @Autowired
    private CommonProperties commonProperties;


    @RequestMapping(value = "/init.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到会员注册页面")
    public String init(HttpServletRequest request, Model model) {
        try {
            logger.info(LOG_PREFIX + "开始验证是否微信客户端请求");
            WechatPayUtil.isWechatClientRequest(request);
            logger.info(LOG_PREFIX + "结束验证是否微信客户端请求,验证通过" );


            String wxurl = WechatClient.getCode(commonProperties.getWechatAppId(), commonProperties.getRedirectURI());
                return "redirect:" + wxurl;


        } catch (BusinessException e1) {
            logger.info(LOG_PREFIX + "收银台初始化失败,失败原因", e1);
            model.addAttribute("errorInfo", e1.getMessage());

            return "/views/initFail";
        } catch (Exception e2) {
            model.addAttribute("errorInfo", "收银台初始化失败,请稍后重试");
            logger.error(LOG_PREFIX + "收银台初始化失败,失败原因", e2);
            return "/views/initFail";
        }

    }


    @RequestMapping(value = "/toGetLocation.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到获取地理位置页面")
    public String toGetLocation() {
        return "/front/test/jsapiticket";

    }

    @RequestMapping(value = "/toWechat.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到会员注册页面")
    public String toMemberRegister() {
        return "/front/test/wechat.html";

    }

    @RequestMapping(value = "/queryOpenId.action",method = RequestMethod.POST)
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询OpenId")
    public String queryOpenId(HttpServletRequest request, Model model){

        try {


            logger.info("开始获取会员OpenId");
            String openId= WechatPayUtil
                    .getWeChatOpenId(request,commonProperties.getWechatAppId(),commonProperties.getWechatSecret());
            logger.info("weixin返回的openId："+openId);
            model.addAttribute("openid",openId);

        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"微信查询OpenId失败，失败原因：",e1);
            model.addAttribute("openid","微信查询OpenId失败，请稍后重试!");
            return  "/front/test/wechat.html";
        }catch (Exception e2){
            model.addAttribute("openid","微信查询OpenId失败,请稍后重试!");
            logger.error(LOG_PREFIX+"微信查询OpenId失败,失败原因",e2);
            return "/front/test/wechat.html";
        }
        logger.info("结束查询微信OpenId，返回数据:{}", model);
        return  "/front/test/wechat.html";

    }


    @RequestMapping("/getJsapiTicket.action")
    @ResponseBody
    public BaseResponse getJsapiTicket(){
        BaseResponse<JsWechatConfig> backResponse=new BaseResponse<>();
        logger.info("开始获取JsapiTicket:" );

        try {
            JsapiTicket jsapiTicket = WechatClient.getTicket();

            //获取签名signature
            String noncestr = UUID.randomUUID().toString();
            Long timestamp = System.currentTimeMillis() / 1000;
            String url=commonProperties.getRedirectURI()+commonProperties.getContextPath()+"/front/toGetLocation.action";
            String str = "jsapi_ticket=" + jsapiTicket.getTicket() + "&noncestr=" + noncestr
                         + "&timestamp=" + timestamp + "&url=" + url;
            //sha1加密
            logger.info("signature 加密前:"+str);
            String signature = SHA1Util.SHA1(str);
            logger.info("signature 加密后:"+signature);

            JsWechatConfig jsWechatConfig = new JsWechatConfig();
            jsWechatConfig.setAppId(commonProperties.getWechatAppId());
            jsWechatConfig.setTimestamp(timestamp);
            jsWechatConfig.setNoncestr(noncestr);
            jsWechatConfig.setSignature(signature);

            backResponse.setResult(jsWechatConfig);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
            logger.info("获取JsapiTicket成功:" + JSON.toJSONString(backResponse));

        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"获取JsapiTicket失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"获取JsapiTicket失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("获取JsapiTicket失败");
        }
        return backResponse;

    }



}